package cn.hfatec.shms.system.codeInfo.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.base.BaseAction;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.system.codeInfo.model.CodeInfoParams;
import cn.hfatec.shms.system.codeInfo.service.CodeInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/system/codeInfo")
public class CodeInfoAction extends BaseAction {

    //服务层
    @Resource(name = "CodeInfoService")
    private CodeInfoService codeInfoService;


    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(String[] codeTypeIds, Model model) {

        List table = codeInfoService.queryCodeInfoTable(codeTypeIds);
        model.addAttribute("codeInfoTable", table);
        return "/system/codeInfo/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(String codeTypeIds, Model model) {
        try {
            list(codeTypeIds.split(","), model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/codeInfo/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Model model) {
        try {
            CodeInfo codeInfo = new CodeInfo();
            model.addAttribute("parentValueList", new ArrayList<CodeInfo>());
            model.addAttribute("codeInfo", codeInfo);
            model.addAttribute("codeTypeList", codeInfoService.getCodeTypeList());
            model.addAttribute("codeInfoList", new ArrayList<CodeInfo>());
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/codeInfo/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            CodeInfo codeInfo = codeInfoService.getCodeInfo(id);
            if (StringUtils.isNotBlank(codeInfo.getParentTypeId())) {
                model.addAttribute("parentValueList", codeInfoService.queryCodeInfoList(codeInfo.getParentTypeId()));
            } else {
                model.addAttribute("parentValueList", new ArrayList());
            }
            model.addAttribute("codeInfo", codeInfo);
            model.addAttribute("codeTypeList", codeInfoService.getCodeTypeList());
            CodeInfoParams codeInfoParams = new CodeInfoParams();
            codeInfoParams.setParentTypeId(codeInfo.getCodeTypeId());
            codeInfoParams.setParentValue(codeInfo.getValue());
            model.addAttribute("codeInfoList", codeInfoService.queryCodeInfoList(codeInfoParams));

            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/codeInfo/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteCodeInfo(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            codeInfoService.deleteCodeInfoBatch(idList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveCodeInfo(@Valid CodeInfo codeInfo, BindingResult result) {

        try {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            codeInfoService.saveCodeInfo(codeInfo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据CodeInfo保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 跳转到新增页
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_CODE_INFO_A','ROLE_CODE_INFO_E')")
    @RequestMapping("/parentValueList")
    @ResponseBody
    public String parentValueList(String codeTypeId, Model model) {
        try {
            CodeInfo codeInfo = new CodeInfo();
            model.addAttribute("codeInfo", codeInfo);
            model.addAttribute("parentValueList", codeInfoService.queryCodeInfoList(codeTypeId));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/codeInfo/selectCodeTypeValue", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

}
